#pragma once
#include <iostream>
#include "Protocol.hpp"

enum
{
    DIVZERO = 1,
    MODZERO,
    OTHEROP
};


class Servercal
{
public:
    Servercal()
    {
    }

    Response CalculateHelper(const Request &req)
    {
        Response resp(0,0);
        switch (req.op_)
        {
        case '+':
            resp.result_ = req.data1_ + req.data2_;
            break;
        case '-':
            resp.result_ = req.data1_ - req.data2_;
            break;
        case '*':
            resp.result_ = req.data1_ * req.data2_;
            break;
        case '/':
            if(req.data2_ == 0) resp.code_ = DIVZERO;
            else resp.result_ = req.data1_ / req.data2_;
            break;
        case '%':
            if(req.data2_ == 0) resp.code_ = MODZERO;
            else resp.result_ = req.data1_ % req.data2_;
            break;
        default:
            resp.code_ = OTHEROP;
            break;
        }

        return resp;
    }

    std::string Calculate(std::string &package)
    {
        std::string content;
        //解包，获取有效载荷
        bool r = DeHeader(package, content);
        if (!r) return "";
        Request req;
        //反序列化，将字符串转化为结构体
        r = req.DeSerialize(content);
        if(!r) return "";

        //计算结果并且存入响应结构体
        Response resp = CalculateHelper(req);
        content = "";
        //序列化，结构体转化字符串
        r = resp.Serialize(content);
        if(!r) return "";
        //封包，添加报头
        content = EnHeader(content);

        return content;
    }

    ~Servercal()
    {
    }

};